package com.yang.job;


import com.yang.mapper.FollowMapper;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import static com.yang.constants.RedisConstants.FOLLOWS_KEY;

/**
 * <p>
 * 刷新关注信息到数据库定时器
 * </p>
 * @author yang
 * @date 2023/8/14
 */
@Component
public class FlushFollowDataJob {
    private static final String PREFIX = FOLLOWS_KEY + "*";
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private FollowMapper followMapper;
    @Resource
    private TransactionTemplate transactionTemplate;

    /**
     * 每天上午10点，下午2点，4点
     */
    @Scheduled(cron = "0 0 10,14,16 * * ?")
    public void flushFollowData2DB() {
        Set<String> keys = stringRedisTemplate.keys(PREFIX);


        if (keys == null || keys.isEmpty()){
            return;
        }
        transactionTemplate.execute((status) -> {

            keys.forEach(key -> {
                Set<String> newFollowData = stringRedisTemplate.opsForSet().members(key);

                if (newFollowData == null || newFollowData.isEmpty()){
                    return;
                }

                long userId = Long.parseLong(key.split(":")[1]);

                List<Long> userIds = newFollowData.stream().map(Long::parseLong).collect(Collectors.toList());


                followMapper.deleteByUserId(userId);
                followMapper.batchInsert(userId,userIds);
            });
            return Boolean.TRUE;

        });

    }
}
